package com.itfreer.bpm.workflow.service.pass;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.bpm.config.entity.BpmTaskConfigEntity;
import com.itfreer.bpm.config.service.IBpmConfigService;
import com.itfreer.bpm.config.service.IBpmTaskConfigService;
import com.itfreer.bpm.flow.api.IBpmProjectEntity;
import com.itfreer.bpm.flow.api.IUserNextTaskUser;
import com.itfreer.bpm.history.entity.BpmHistoryEntity;
import com.itfreer.bpm.messager.BpmMessage;
import com.itfreer.bpm.option.para.NextTaskInfo;
import com.itfreer.bpm.option.para.NextTaskType;
import com.itfreer.bpm.option.para.OptionInfo;
import com.itfreer.bpm.option.para.OptionType;
import com.itfreer.bpm.option.para.TaskInfo;
import com.itfreer.bpm.option.para.TaskType;
import com.itfreer.bpm.power.para.UserInfo;
import com.itfreer.bpm.workflow.drive.IWorkFlowDrive;
import com.itfreer.bpm.workflow.option.SignCommonTask;
import com.itfreer.bpm.workflow.option.SignMultiTask;
import com.itfreer.bpm.workflow.service.BpmWorkFlowCommonSignImp;
import com.itfreer.bpm.workflow.userrole.IUserRole;
import com.itfreer.bpm.workflow.utils.BpmApprovalHistoryUtil;
import com.itfreer.bpm.workflow.utils.BpmHistoryEditUtil;
import com.itfreer.bpm.workflow.utils.BpmHistoryQueryUtil;
import com.itfreer.bpm.workflow.utils.BpmNextTaskUtils;
import com.itfreer.bpm.workflow.utils.BpmUserAuthUtils;

/**
 * 流程通过实现类
 * @author Administrator
 *
 */
@Component
public class BpmWorkFlowPassImp {
	
	@Autowired
	private IBpmTaskConfigService bpmTaskConfigService;

	/**
	 * 流程驱动服务
	 */
	@Autowired
	protected IWorkFlowDrive workFlowDrive;
	
	/**
	 * 构建历史帮转工具
	 */
	@Autowired
	BpmHistoryEditUtil historyEditUtl;
	
	/**
	 * 构建用户审批历史
	 */
	@Autowired
	BpmApprovalHistoryUtil approvalUtil;
	
	/**
	 * 用户授权工具
	 */
	@Autowired
	BpmUserAuthUtils userAuthUtils;
	
	/**
	 * 审批过程查询接口
	 */
	@Autowired
	BpmHistoryQueryUtil historyQueryUtil;
	
	/**
	 * 用户角色接口
	 */
	@Autowired
	IUserRole userRole;
	/**
	 * 用户自定义操作下一步审批人接口
	 */
	@Autowired(required=false)
	IUserNextTaskUser userNextTaskUser;
	
	/**
	 * 下一个环节工具
	 */
	@Autowired
	BpmNextTaskUtils nextTaskUtils;
	
	/**
	 * 单节点会签提交
	 */
	@Autowired
	SignMultiTask signmultiTask;
	
	/**
	 * 多节点选择节点
	 */
	@Autowired
	SignCommonTask signCommonTask;
	
	/**
	 * 通用流程驱动操作
	 */
	@Autowired
	BpmWorkFlowCommonSignImp commonSign;
	
	/**
	 * 获取流程下一个节点信息
	 */
	public OptionInfo getNextTask(String bpmkey, IBpmProjectEntity entity, List editHistory, UserInfo user) {
		OptionInfo info=new OptionInfo();
		info.setbpmkey(bpmkey);
		String sexeid=entity.getSexeid();
		boolean startProcess=false;
		if(sexeid==null || "".equals(sexeid.trim())) {
			startProcess=true;
			//1、启动流程
			sexeid= workFlowDrive.startFlow(bpmkey);
			entity.setSexeid(sexeid);
			
			//2、流程启动时，只能处理简单的一个节点方式
			List<TaskInfo> lstCTasks=workFlowDrive.getCurrentTask(sexeid);
			if(lstCTasks==null || lstCTasks.isEmpty() || lstCTasks.size()>1) {
				throw new RuntimeException("系统暂时出路不了多节点同时处理问题");
			}
			TaskInfo userTask=lstCTasks.get(0);
			List<UserInfo> lstUser=new ArrayList<UserInfo>();
			lstUser.add(user);
			userTask.setUser(lstUser);
			//info.setcTask(userTask);
			historyEditUtl.addStartHistory(sexeid, bpmkey,userTask.getTaskName(), user, entity);
			
			//3、第一个节点历史配置
			BpmHistoryEntity history1 =historyEditUtl.CreateHistory(sexeid, bpmkey, user, userTask, entity);
			//a、设置项目来源信息
			history1.setfromtaskdefname("开始");
			history1.setfromtaskdefid("U0");
			
			history1.setfromassigneesid(user.getUserId());
			history1.setfromassigneesname(user.getUserName());
			history1.setfromorgid(user.getUserOrgCode());
			history1.setfromorgname(user.getUserOrgName());
			//b、设置项目历史状态信息
			history1.sethistorystatus("21");
			//c、设置项目历史审批人问题
			String sassignees=","+user.getUserId()+","+user.getUserName();
			history1.setsassignees(sassignees);
			//d、设置项目待审批人信息
			history1.setToptassigneese(sassignees);
			history1.setSread("0");
			//e、设置项目的下一个环节
			history1.setTasktype(workFlowDrive.getTaskStringType(bpmkey, userTask.getTaskdefinedid()));
			history1.setNexttask(nextTaskUtils.getNextTaskInfo(sexeid, bpmkey,  userTask.getTaskdefinedid(),entity).getNextTaskName());
			historyEditUtl.addandSaveEntity(history1);
			
			
			//0、删除草稿记录（新添加功能）
			this.historyEditUtl.deleteDraft(entity.getId());
		}
		info.setSexeid(sexeid);

		
		HashMap<String,Object> work_where=new HashMap<String,Object>();
		work_where.put("sexeid:=", sexeid);
		//检查校验是否是超级管理员
		if(!user.isSuperAdmin()) {
			work_where.put("toptassigneese:like",user.getUserId());
		}
		List<BpmHistoryEntity>toWorkList= historyQueryUtil.getWorkEntitys(null, work_where, null, 1000, 1);
		
		//处理当前环节
		List<TaskInfo> ctasks=new ArrayList<TaskInfo>();
		for(BpmHistoryEntity work:toWorkList) {
			TaskInfo task=new TaskInfo();
			task.setTaskdefinedid(work.gettaskdefid());
			task.setTaskName(work.gettaskdefname());
			ctasks.add(task);
		}
		info.setcTask(ctasks);
		
		//处理掉下一个环节信息
		String ctaskid=null;
		if(toWorkList!=null && toWorkList.size()>0) {
			ctaskid=toWorkList.get(0).gettaskdefid();
		}
		NextTaskInfo nextTaskInfo= this.nextTaskUtils.getNextTaskInfo(sexeid,bpmkey, ctaskid,entity);
		if(nextTaskInfo!=null 
				&& nextTaskInfo.getNextTask()!=null 
				&& nextTaskInfo.getNextTask().size()>0) {
			//处理项目类型
			if(nextTaskInfo.getNextTaskType().equals(NextTaskType.CommonTask)) {
				info.setOptiontype(OptionType.CommonSign);
			}else if(nextTaskInfo.getNextTaskType().equals(NextTaskType.ExclusiveTask)) {
				info.setOptiontype(OptionType.ExclusiveSign);
			}else if(nextTaskInfo.getNextTaskType().equals(NextTaskType.InclusiveTask)) {
				info.setOptiontype(OptionType.InclusiveSign);
			}else if(nextTaskInfo.getNextTaskType().equals(NextTaskType.MultiSingleTask)) {
				info.setOptiontype(OptionType.MuliSingleSign);
			}else if(nextTaskInfo.getNextTaskType().equals(NextTaskType.ParallelTask)) {
				info.setOptiontype(OptionType.ParallelSign);
			}
			
			/**
			 * 获取流程的第一个环节
			 */
			BpmHistoryEntity starth=historyQueryUtil.getStartHistory(sexeid);
			for(int k=0;k<nextTaskInfo.getNextTask().size();k++) {
				TaskInfo task=nextTaskInfo.getNextTask().get(k);
				String taskid=task.getTaskdefinedid();
				//3-f流程环节配置信息
				HashMap<String,Object> task_where=new HashMap<String,Object>();
				task_where.put("actdefid:=", bpmkey);
				task_where.put("taskdefid:=", taskid);
				List<UserInfo> lstuser=new ArrayList<UserInfo>();
				List<BpmTaskConfigEntity> task_configs=bpmTaskConfigService.getEntitys(null, task_where, null, 1, 1);
				
				//如果配置信息里面没有配置角色时处理方式
				if(task_configs==null || task_configs.size()<1 
						|| task_configs.get(0).getUserrole()==null
						|| "".equals(task_configs.get(0).getUserrole().trim())) {
					
					lstuser.add(user);
					task.setUser(lstuser);
				}else {
					//处理配置节点的用户信息
					lstuser=userRole.getUserForRole(task_configs.get(0).getUserrole().trim());
				}
				String userexpress=task_configs.get(0).getUserexpress();
				if(userexpress!=null && !"".equals(userexpress.trim())
						&& lstuser!=null && lstuser.size()>0) {
					List<UserInfo> nlstuser=new ArrayList<UserInfo>();
					try {
						
						for(UserInfo iuser:lstuser) {
							String temp=userexpress.trim();
							temp=temp.replace("{SP_ORGID}", iuser.getUserOrgCode());
							if(startProcess) {
								String jborgid=user.getUserOrgCode();
								temp=temp.replace("{JB_ORGID}", jborgid);
							}else if(starth!=null) {
								String jborgid=starth.getoptorgid();
								temp=temp.replace("{JB_ORGID}", jborgid);
							}
							
							ScriptEngineManager factory = new ScriptEngineManager();
							ScriptEngine scriptEngine = factory.getEngineByName("javascript");
							
							try {
								Object obj = scriptEngine.eval(temp);
								if (obj != null && obj instanceof Boolean && (Boolean) obj) {
									nlstuser.add(iuser);
								}else if(!(obj instanceof Boolean)){
									Invocable inv = (Invocable) scriptEngine;
									obj = (Object) inv.invokeFunction("test");
									
									if (obj != null && obj instanceof String) {
										nlstuser.add(iuser);
									}else if (obj != null && obj instanceof Boolean && (Boolean) obj) {
										nlstuser.add(iuser);
									}
									
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}catch(Exception e) {
					}
					if(userNextTaskUser!=null) {
						userNextTaskUser.verifyUser(lstuser, nlstuser, ctasks, task, entity, user);
					}
					lstuser=nlstuser;
				}
				if(lstuser==null || lstuser.size()<1) {
					lstuser=new ArrayList<UserInfo>();
					lstuser.add(user);
				}
				task.setUser(lstuser);
			}
		}
		info.setNextTask(nextTaskInfo.getNextTask());
		
		//设置项目默认选择问题
		if(OptionType.CommonSign.equals(info.getOptiontype())
				|| OptionType.InclusiveSign.equals(info.getOptiontype())
				|| OptionType.ParallelSign.equals(info.getOptiontype())
				|| OptionType.MuliSingleSign.equals(info.getOptiontype())) {
			if(info.getNextTask()!=null) {
				for(int k=0;k<info.getNextTask().size();k++) {
					info.getNextTask().get(k).setTaskSelect(true);
					info.getNextTask().get(k).setAllUserSelect();
				}
			}
		}else if(OptionType.ExclusiveSign.equals(info.getOptiontype())) {
			if(info.getNextTask()!=null && info.getNextTask().size()>0) {
				info.getNextTask().get(0).setTaskSelect(true);
				info.getNextTask().get(0).setAllUserSelect();
			}
		}
		
		//当环节没有下一个环节，推送流程办结事项
		if(info.getNextTask()==null || info.getNextTask().size()<1) {
			info.setOptiontype(OptionType.EndSign);
		}
		
		//保存历史数据
		historyEditUtl.updateList(editHistory);
		return info;
	}
	
	/**
	 * 项目通过提交的代码
	 */
	public BpmMessage signTask(OptionInfo oInfo, IBpmProjectEntity entity, UserInfo user) {
		return this.commonSign.signTask(oInfo, entity, user, "提交");
	}
}
